package com.marvels.system.permission.service.impl;


import java.util.Arrays;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.marvels.common.exception.MarvelsBusinessException;
import com.marvels.common.utils.CacheUtils;
import com.marvels.common.utils.MarvelsLogUtil;
import com.marvels.common.utils.ServerProperties;
import com.marvels.common.utils.ShaUtils;
import com.marvels.system.permission.dao.SysUserDao;
import com.marvels.system.permission.dto.SysRoleDTO;
import com.marvels.system.permission.dto.SysUserDTO;
import com.marvels.system.permission.dto.SysUserParamDTO;
import com.marvels.system.permission.dto.SysUserRoleDTO;
import com.marvels.system.permission.service.SysUserService;

import cn.hutool.core.util.StrUtil;

@Service
public class SysUserServiceImpl implements SysUserService {
	@Autowired
	private SysUserDao sysUserDao;
	
	@Value("${config.properties.path}")
	private String configPropertiesPath;
	/**
     * 分页查询
     * @param pageNo 页号
     * @param pageSize 每页显示记录数
     * @return
     */
	@Override
	public Page<SysUserDTO> getUserPageByOrgCode(SysUserDTO conditions,Integer pageNo,Integer pageSize)throws MarvelsBusinessException {
		if(pageNo <= 0){
			pageNo = 1;
		}
		if(pageSize <=0){
			pageSize = 20;
		}
		if(StringUtils.isNotEmpty(conditions.getSortBy())){
			PageHelper.orderBy(conditions.getSortBy()+" "+conditions.getSortType());
		}
		PageHelper.startPage(pageNo, pageSize);
		MarvelsLogUtil.getInstance().info(pageNo + pageSize + "分页查询conditions"+conditions);
		Page<SysUserDTO> userPage = null;
		String ignoreUserCodes= ServerProperties.getValue(configPropertiesPath, "common.properties", "ignore_user_code");
		if(StrUtil.isNotEmpty(ignoreUserCodes)){
			conditions.setIgnoreUserCodeList(Arrays.asList(ignoreUserCodes.split(",")));
		}
		if("1".equals(conditions.getFlag()))
			userPage = sysUserDao.selectUserPageByOrgCode1(conditions);
		else
			userPage = sysUserDao.selectUserPageByOrgCode(conditions);
        return userPage;
	}


	@Override
	public int addUser(SysUserDTO user) throws MarvelsBusinessException {
		//校验用户必填信息是否为空
		checkUserBaseInfo(user);
		if(!equalsPwd(user.getUserPwd(),user.getConfirmPwd())){
			throw new MarvelsBusinessException("密码和确认密码不一致");
		}
		if(isUserCodeExistence(user.getUserCode())){
			throw new MarvelsBusinessException("用户编码"+user.getUserCode()+"已存在");
		}
		if(isUserNameExistence(user.getUserNamep())){
			throw new MarvelsBusinessException("用户名称"+user.getUserNamep()+"已存在");
		}
		int n = 0;
		//新增用户
		user.setUserPwd(ShaUtils.Encrypt(user.getUserPwd(), "MD5"));
		user.setCreatedBy(CacheUtils.getCacheUser().getUserName());
		user.setUpdatedBy(CacheUtils.getCacheUser().getUserName());
		user.setUserNamep(user.getUserCode());
		n = sysUserDao.insert(user);
		//新增用户角色关系
		n += insertRelation(user.getRoles());
		return n;
	}
	
	/**
	 * 校验用户必填信息是否为空
	 * @param user
	 * @throws MarvelsBusinessException
	 */
	private void checkUserBaseInfo(SysUserDTO user) throws MarvelsBusinessException{
		if(user == null){
			throw new MarvelsBusinessException("入参为空");
		}
		if(StringUtils.isEmpty(user.getOrgCode())){
			throw new MarvelsBusinessException("组织机构编码为空");
		}
		if(StringUtils.isEmpty(user.getUserCode())){
			throw new MarvelsBusinessException("用户编码为空");
		}
//		if(StringUtils.isEmpty(user.getUserNamep())){
//			throw new MarvelsBusinessException("用户名为空");
//		}
		if(StringUtils.isEmpty(user.getUserPwd())){
			throw new MarvelsBusinessException("用户密码为空");
		}
		if(StringUtils.isEmpty(user.getRealName())){
			throw new MarvelsBusinessException("用户真实姓名为空");
		}
//		if(StringUtils.isEmpty(user.getIdCardNo())){
//			throw new MarvelsBusinessException("身份证号为空");
//		}
//		if(StringUtils.isEmpty(user.getEmail())){
//			throw new MarvelsBusinessException("用户邮箱为空");
//		}
		if(StringUtils.isEmpty(user.getMobileNo())){
			throw new MarvelsBusinessException("手机号为空");
		}
		if(StringUtils.isEmpty(user.getConfirmPwd())){
			throw new MarvelsBusinessException("确认密码为空");
		}
	}
	
	/**
	 * 密码和确认密码比较
	 * @param userPwd
	 * @param confirmPwd
	 * @return
	 */
	private boolean equalsPwd(String userPwd,String confirmPwd){
		return StringUtils.equals(userPwd, confirmPwd);
	}
	
	/**
	 * 查询用户编码是否已存在
	 * @param code
	 * @return
	 */
	private boolean isUserCodeExistence(String code){
		boolean isExisted = false;
		int count = sysUserDao.selectCountByUserCode(code);
		if(count > 0){
			isExisted = true;
		}
		return isExisted;
	}
	
	/**
	 * 查询用户名是否已存在
	 * @param name
	 * @return
	 */
	private boolean isUserNameExistence(String name){
		boolean isExisted = false;
		int count = sysUserDao.selectCountByUserName(name);
		if(count > 0){
			isExisted = true;
		}
		return isExisted;
	}
	
	/**
	 * 新增用户角色关系
	 * @param list
	 * @return
	 * @throws MarvelsBusinessException
	 */
	private int insertRelation(List<SysUserRoleDTO> list) throws MarvelsBusinessException{
		int n = 0;
		if(CollectionUtils.isNotEmpty(list)){
			for(SysUserRoleDTO ur : list){
				ur.setCreatedBy(CacheUtils.getCacheUser().getUserName());
				ur.setUpdatedBy(CacheUtils.getCacheUser().getUserName());
			}
			n = sysUserDao.insertRelation(list);
		}
		return n;
	}
	
	@Override
	public SysUserDTO getUserById(SysUserDTO user) throws MarvelsBusinessException {
		isPrimaryKeyEmpty(user);
		return sysUserDao.selectByPrimaryKey(user);
	}
	
	private void isPrimaryKeyEmpty(SysUserDTO user) throws MarvelsBusinessException{
		if(user == null){
			throw new MarvelsBusinessException("入参为空");
		}
		Integer userId = user.getUserId();
		if(userId==null || userId<=0){
			throw new MarvelsBusinessException("用户id为空");
		}
	}

	@Override
	public int updateUser(SysUserDTO user) throws MarvelsBusinessException {
		isPrimaryKeyEmpty(user);
		if(StringUtils.isEmpty(user.getUserCode())){
			throw new MarvelsBusinessException("用户编码为空");
		}
		user.setUpdatedBy(CacheUtils.getCacheUser().getUserName());
		if(StringUtils.isNotEmpty(user.getUserCode())){
			user.setUserNamep(user.getUserCode());
		}
		//更新用户
		int n = sysUserDao.updateByPrimaryKey(user);
		//删除用户角色关系
		sysUserDao.deleteRelation(user);
		//重新新增用户角色关系
		insertRelation(user.getRoles());
		return n;
	}
	
	@Override
	public int deleteUser(SysUserDTO user) throws MarvelsBusinessException {
		isPrimaryKeyEmpty(user);
		if(StringUtils.isEmpty(user.getUserCode())){
			throw new MarvelsBusinessException("用户编码为空");
		}
		user.setUpdatedBy(CacheUtils.getCacheUser().getUserName());
		int n = sysUserDao.deleteByPrimaryKey(user);
		//删除用户角色关系
		sysUserDao.deleteRelation(user);
		return n;
	}


	@Override
	public Page<SysUserDTO> selectUserList()throws MarvelsBusinessException {
		// TODO Auto-generated method stub
		return sysUserDao.selectUserList();
	}


	@Override
	public Integer selectFacesigRoleNumber() throws MarvelsBusinessException {
		// TODO Auto-generated method stub
		return sysUserDao.selectFacesigRoleNumber();
	}


	@Override
	public SysUserDTO getUserByUserCode(String userCode) throws MarvelsBusinessException {
		// TODO Auto-generated method stub
		SysUserDTO dto = new SysUserDTO();
		dto.setUserCode(userCode);
		return sysUserDao.selectSysUser(dto);
	}


	@Override
	public List<SysUserDTO> selectUserByRoleCode(String roleCode) throws MarvelsBusinessException {
		SysRoleDTO newDto = new SysRoleDTO();
		newDto.setRoleCode(roleCode);
		String ignoreUserCodes= ServerProperties.getValue(configPropertiesPath, "common.properties", "ignore_user_code");
		if(StrUtil.isNotEmpty(ignoreUserCodes)){
			newDto.setIgnoreUserCodeList(Arrays.asList(ignoreUserCodes.split(",")));
		}
		return sysUserDao.selectUserByRoleCode(newDto);
	}


	@Override
	public List<SysUserDTO> querySysUsers(SysUserParamDTO sysUserParamDTO) throws MarvelsBusinessException {
		return sysUserDao.querySysUsers(sysUserParamDTO);
	}


	@Override
	public List<SysUserDTO> selectUserListIgnore(List<String> ignoreUserCodeList) throws MarvelsBusinessException {
		return sysUserDao.selectUserListIgnore(ignoreUserCodeList);
	}
	public static void main(String[] args) {
		System.out.println(ShaUtils.Encrypt("guobin123", "MD5"));
	}
}
